/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\utils\OSS-upload\ossService.ts
 * @Date: 2022-05-25 17:06:39
 * @LastEditTime: 2022-05-26 14:55:35
 */
import { http } from "@/lib";
import apis from '@/apis'
import { IOssConfig } from './ossClientCreator';
import dayjs from "dayjs";


const fileKeyFormat = (modelPath, file, key?) => {
  const { name } = file
  const date = dayjs().format('YYYY-MM-DD')
  const time = dayjs().format('YYYYMMDDHHmmss')
  const fileName = key ? '/' + key : time + name
  let pathName = modelPath
  key = pathName + '/' + date + '/' + fileName
  return key
}

export async function getOssConfig(): Promise<IOssConfig> {
  let res = await http.get(apis.OSSTstToken)
  return res.data;
}

export async function multipartUpload(ossClient: any, path: string, file: File) {
  let ossRes = await ossClient.multipartUpload(path, file);
  let url: string = '';
  if (ossRes && ossRes.name) {
    url = `http://${ossClient.options.bucket}.${ossClient.options.endpoint.host}/${ossRes.name}`;
  } else {
    throw new Error('上传失败');
  }
  ossClient = null;
  return url;
}

export async function put(ossClient: any, path: string, file: File) {
  let key = fileKeyFormat(path, file)
  let ossRes = await ossClient.put(key, file)
  let url: string = '';
  if (ossRes && ossRes.url) {
    url = ossRes.url
  } else {
    throw new Error('上传失败');
  }
  ossClient = null;
  return url;
}

export async function upload(ossClient: any, path: string, file: File) {
  let size = file.size / 1024;
  if (size > 100 * 1024) {
   throw new Error( '附件大小不能超过100M');
  }
  if (size > 50 * 1024) {
    return await multipartUpload(ossClient, path, file);
  }
  let result = await ossClient.put(path, file)
  let url: string = '';
  if (result && result.name) {
      console.log('result', result)
    url = `http://${ossClient.options.bucket}.${ossClient.options.endpoint.host}/${result.name}`;
  } else {
    throw new Error('上传失败');
  }
  ossClient = null;
  return url;
}

export default {
  getOssConfig,
  multipartUpload,
  put,
  upload,
};